import javax.swing.tree.TreeNode;
import java.util.*;

public class DAY0326 {
    public boolean isValid(String s) {
        int n=s.length();
        if(n%2==1){
            return false;
        }

        Map<Character,Character> hashmap=new HashMap<Character, Character>(){{
            put(')', '(');
            put(']', '[');
            put('}', '{');
        }};
        Deque<Character> stock=new LinkedList<>();
        for (int i = 0; i < n; i++) {
            char ch = s.charAt(i);
            if (hashmap.containsKey(ch)) {
                if (stock.isEmpty() || stock.peek() !=hashmap.get(ch)) {
                    return false;
                }
                stock.pop();
            } else {
                stock.push(ch);
            }

        }
        return  stock.isEmpty();
    }

    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer>res=new ArrayList<>();
        preorder2(root,res);
        return res;
    }
    public void preorder2(TreeNode root, List<Integer> res) {
        if (root == null) {
            return;
        }
        preorder2(root.left, res)
        ;preorder2(root.right, res);
        res.add(root.val);
    }
      public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }

    public boolean isSymmetric(TreeNode root) {
        return check(root,root);
    }
    public boolean check(TreeNode p, TreeNode q) {
        if(p==null&&q==null){
            return true;
        }
        if(p==null||q==null){
            return false;
        }
        return q.val==p.val&&check(q.left,p.right)&&check(q.right,p.left);
    }

    public int maxDepth(TreeNode root) {
        if(root==null){
            return 0;
        }
        int leftHeight=maxDepth(root.left);
        int rightHeight=maxDepth(root.right);
        return (Math.max(leftHeight,rightHeight))+1;
    }

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<List<Integer>>();
        if (root == null) {
            return ret;
        }

        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            List<Integer> level = new ArrayList<Integer>();
            int currentLevelSize = queue.size();
            for (int i = 1; i <= currentLevelSize; ++i) {
                TreeNode node = queue.poll();
                level.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            ret.add(level);
        }

        return ret;
    }
}
